import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/model/use_request/use_request_model.dart';
import 'package:ls_work/net/response/use_request/use_request_record_detail_data.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/ui/select_employee_page.dart';
import 'package:ls_work/util/ext_utils.dart';
import 'package:ls_work/viewmodel/new_yyt_view_model.dart';
import 'package:ls_work/widgets/bottom_input_widget.dart';

import '../../model/office_model.dart';
import '../../net/response/department_list_data.dart';
import '../../net/response/office_list_tree_data.dart';
import '../../net/response/use_request/goods_request_list_data.dart';
import '../../net/response/user_info_data.dart';
import '../../res/gaps.dart';
import '../../ui/service_order/department_list_page.dart';
import '../../ui/use_request/choose_goods_page.dart';
import '../../ui/use_request/office_list_page.dart';
import '../../widgets/title_value_widget.dart';

class AddUseRequestViewModel extends BaseViewModel {
  num? recordId;

  AddUseRequestViewModel(BuildContext context, {this.recordId})
      : super(context);

  UserInfoData? get userInfo => NewYytViewModel.userInfo;
  var officeModel = OfficeModel();
  var useRequestModel = UseRequestModel();

  var officeName = "";
  var officeId = "";

  var userName = "";
  var userId = "";

  var officePatentId = "";
  var oddNumbers = "";
  var canAudite = true;
  var selectList = <GoodsRequestListData>[];
  dynamic approveType;
  dynamic approveTypeName;
  dynamic status;

  var useTypeList = [
    PickerDataWithIdModel(pickName: '常规入库物资',pickId: '0'),
    PickerDataWithIdModel(pickName: '捐赠入库物资',pickId: '1'),
  ];

  PickerDataWithIdModel? useType;


  @override
  void onCreated() {
    super.onCreated();
    useType = useTypeList.first;
    if (recordId != null) {
      getDetailData();
    } else {
      officeName = userInfo?.officeName??"";
      officeId = userInfo?.officeId??"";
      userName = userInfo?.name??"";
      userId = userInfo?.id.toString()??"";
      getOfficePatent();
      notifyListeners();
    }
  }

  void selectUseType(){
    DataPickerView(context, useTypeList,onSubmitListener: (p1,p2,p3){
      var item =  useTypeList[p1];
      if(useType!=item){
        useType = item;
        selectList.clear();
      }
      notifyListeners();
    }).show();
  }

  Future<void> getDetailData() async {
    showLoadingState();
    try {
      var detail = await useRequestModel.requestDetail(recordId.toString());
      userName = detail.applyPerson??"";
      userId = detail.applyPersonId.toString();
      officeId = detail.officeId.toString();
      officeName = detail.office??"";
      selectList = (detail.logisticsMaterialApplicationDetailBeans??[])
          .map((e) => e.toRequestGoods(officeId))
          .toList();
      oddNumbers = detail.applicationNo??"";
      canAudite = detail.canAudite??false;
      approveTypeName = detail.bpmTypeName;
      approveType = detail.bpmType;
      status = detail.status;
      var list = useTypeList.where((element) => detail.useRange.toString() == element.pickId);
      if(list.isNotEmpty){
        useType = list.first;
      }
      showContent();
    } catch (e) {
      showErrorState(NetErrorUtils.getNetError(e));
    }
  }

  void selectEmployee(){
    Go().push(SelectEmployeePage(onSelectListener: (employee){
      Go().pop();
      userId = employee.id??"";
      userName = employee.name??"";
      notifyListeners();
    },officeId: officeId,));
  }

  Future<void> getOfficePatent() async {
    if (officeId.isNullOrEmpty()) {
      return;
    }
    var parentData = await officeModel.infoData(officeId);
    if (parentData != null) {
      officePatentId = parentData.rootId.toString();
    }
  }

  Future<void> addRequestClick() async {
    GoodsRequestListData? good = await Go().push(ChooseGoodsPage(useRange: useType?.pickId,));
    if (good != null) {
      if (!selectList.contains(good)) {
        good.selectNumber = 1;
        selectList.add(good);
        getApproveType();
        notifyListeners();
      }
    }
  }

  Map<String, dynamic>? getApproveType() {
    // var list =  selectList.map((e) => e.assetTypeName).toList();
    var list = <String>[];
    for (var item in selectList) {
      if (!list.contains(item.assetTypeName)) {
        list.add(item.assetTypeName??"");
      }
    }
    if (list.length >= 2) {
      approveType = 2;
      approveTypeName = "混合审批";
    }
    if (list.length == 1) {
      if (list[0] == "固定资产") {
        approveType = 1;
        approveTypeName = "固定资产审批";
      }

      if (list[0] == '消耗品' || list[0] == '低耗品') {
        approveType = 0;
        approveTypeName = "常规审批";
      }
    }
  }

  Widget contentView() {
    var canChange = (status==null||status==3);
    return Column(
      children: [
        TitleValueWidget(
          "申请部门",
          text: officeName,
          showArrow: canChange,
        ).onTap(() async {
          if(!canChange){
            return;
          }
          await selectDepartment();
        }),
        Gaps.dividerLine,
        TitleValueWidget(
          "申请人",
          text: userName,
          showArrow: canChange,
        ).onTap(() {
          if(!canChange){
            return;
          }
          selectEmployee();
        }),

        Gaps.dividerLine,
        TitleValueWidget(
          "入库类型",
          text: useType?.pickName??"",
          showArrow: canChange,
        ).onTap(() {
          if(!canChange){
            return;
          }
          selectUseType();
        }),
        Gaps.dividerLine,
        TitleValueWidget(
          "申请物资",
          rightWeight: (status==null||status==3)? TextButton(
            onPressed: () {
              addRequestClick();
            },
            child: Text(
              "新增物资",
              style: TextStyle(color: Colors.white),
            ),
            style: ButtonStyle(
                backgroundColor: WidgetStateProperty.all(Colors.blue)),
          ):Container(),
          hint: "",
          padding: EdgeInsets.symmetric(horizontal: 16),
        ),
        if (selectList.isNotEmpty) ...[
          Row(
            children: [
              CommonText('物资名称').setWeight(1),
              CommonText('物资属性').setWeight(1),
              CommonText('单位').setWeight(1),
              CommonText('申请数量').setWeight(1),
            ],
          ).addToContainer(
              margin: EdgeInsets.symmetric(horizontal: 16, vertical: 15)),
          DashLine(
            axis: Axis.horizontal,
            dashedWidth: 4,
            count: 40,
            dashedHeight: 1,
            color: Colors.grey,
          ).addToContainer(margin: EdgeInsets.symmetric(horizontal: 16)),
          ListView(
            children: selectList.map((e) {
              return Slidable(
                child: Row(
                  children: [
                    CommonText(e.materialName).setWeight(1),
                    CommonText(e.assetTypeName ?? "").setWeight(1),
                    CommonText(e.unit ?? "").setWeight(1),
                    Row(
                      children: [
                        if(canChange)
                        Icon(
                          Icons.remove_circle_outline,
                          color: Colors.blue,
                        ).onTap(() {
                          if (e.selectNumber == 1) {
                            selectList.remove(e);
                          } else {
                            e.selectNumber--;
                          }
                          notifyListeners();
                        }),
                        CommonText('${e.selectNumber.d}',
                                textAlign: TextAlign.center)
                            .onTap(() {
                          showBottomInput(context,
                              title: "申请数量",
                              content: e.selectNumber.d.toString(),
                              keyboard: CommonInputType.numberAndDecimal,
                              onSubmit: (str) {
                            var number = num.parse(str);
                            if (e.total != null && number > e.total) {
                              showToast("不可超过库存数量");
                            } else {
                              e.selectNumber = num.parse(str);
                              notifyListeners();
                            }
                          });
                        }).setWeight(1),

                        if(canChange)
                        Icon(
                          Icons.add_circle_outline,
                          color: Colors.blue,
                        ).onTap(() {
                          if (e.total != null && e.selectNumber >= e.total) {
                            showToast("不可超过库存数量");
                          } else {
                            e.selectNumber++;
                            notifyListeners();
                          }
                        }),
                      ],
                    ).setWeight(1),
                  ],
                ).addToContainer(
                    margin: EdgeInsets.symmetric(horizontal: 16, vertical: 15)),
                endActionPane: canChange? ActionPane(
                  motion: const StretchMotion(),
                  children: [
                    SlidableAction(
                      onPressed: (context) {
                        selectList.remove(e);
                        notifyListeners();
                      },
                      label: "删除",
                      spacing: 2,
                      backgroundColor: Colors.red,
                      flex: 1,
                    )
                  ],
                ):null,
              );
            }).toList(),
          ).setWeight(1),
        ],
        if (selectList.isEmpty) Container().setWeight(1),

        (status==null||status==3)?
        Row(
          children: [
            Container(
              width: 16,
            ),
            TextButton(
              onPressed: () {
                finish();
              },
              child: CommonText("取消", textColor: Colors.blue),
              style: ButtonStyle(
                  shape: WidgetStateProperty.all(RoundedRectangleBorder(
                      borderRadius: 4.borderRadius,
                      side: BorderSide(color: Colors.blue, width: 1)))),
            ).setWeight(1),
            if (selectList.isNotEmpty) ...[
              Container(
                width: 12,
              ),
              TextButton(
                onPressed: () {
                  submitRequest(0);
                },
                child: CommonText("保存草稿", textColor: Colors.white),
                style: ButtonStyle(
                    backgroundColor:
                        WidgetStateProperty.all(Colours.app_main),
                    shape: WidgetStateProperty.all(
                        RoundedRectangleBorder(borderRadius: 4.borderRadius))),
              ).setWeight(1),
            ],
            if (selectList.isNotEmpty) ...[
              Container(
                width: 12,
              ),
              TextButton(
                onPressed: () {
                  submitRequest(1);
                },
                child: CommonText("提交审批", textColor: Colors.white),
                style: ButtonStyle(
                    backgroundColor: WidgetStateProperty.all(Colors.blue),
                    shape: WidgetStateProperty.all(
                        RoundedRectangleBorder(borderRadius: 4.borderRadius))),
              ).setWeight(1),
            ],
            Container(
              width: 16,
            ),
          ],
        ):
        -1==status?Row(
          children: [
            Container(width: 16,),
            TextButton(onPressed: (){
              showApplyDialog(context: context, onSubmit: (){
                deleteRequest();
              },message: "确定要撤销审批吗？");
            }, child: CommonText('撤销审批',textColor: Colors.white),
            style: ButtonStyle(
              backgroundColor: WidgetStateProperty.all(Colors.blue)
            ),)
          ],
        ): Container(),
        Container(
          height: 15,
        )
      ],
    );
  }

  Future<void> selectDepartment() async {
    OfficeListTreeData? data = await Go().push(OfficeListPage());
    // DepartmentListData data = await Go().push(DepartmentListPage());
    if (data != null) {
      officeName = data.officeName??"";
      officeId = data.id.toString();
      userName = "";
      userId = "";
      getOfficePatent();
      notifyListeners();
    }
  }

  ///提交
  ///[type] 0保存 1提交
  Future<void> submitRequest(dynamic type) async {
    showLoadingDialog(msg: '提交中...');
    try {
      var result = await useRequestModel.addRequest(
          officeId: officePatentId,
          officeChildrenId: officeId,
          applyPersonId: userId,
          logisticsMaterialApplicationDetailBeans:
              selectList.map((e) => e.toSubmitInfo(officePatentId)).toList(),
          saveOrSubmit: type,
          bpmType: approveType,
          bpmTypeName: approveTypeName,
          person: userName,
          oddNumbers: oddNumbers,
      canAudite: canAudite,id: recordId,useRange: useType?.pickId??"");
      await Future.delayed(Duration(milliseconds: 1000));
      hideDialog();
      showToast("提交成功");
      sendMessage(SendMessageEvent(MessageConfig.ADD_REQUEST_SUCCESS));

      finish();
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  ///取消申请
  Future<void> deleteRequest() async {
    showLoadingDialog();
    try{
      await useRequestModel.deleteRequest(recordId);
      await Future.delayed(Duration(milliseconds: 1000));
      hideDialog();
      showToast("提交成功");
      sendMessage(SendMessageEvent(MessageConfig.ADD_REQUEST_SUCCESS));
      finish();
    }catch(e){
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }
}

class SelectGoodsInfo {
  String? name;
  String? assetsType;
  String? unit;
  int? number;
  num? id;
  num? total;

  SelectGoodsInfo(
      {this.name,
      this.assetsType,
      this.unit,
      this.number = 1,
      this.id,
      this.total});
}

extension GoodsEx on GoodsRequestListData {
  SelectGoodsInfo toSelectData() {
    return SelectGoodsInfo(
        name: this.materialName,
        assetsType: this.assetTypeName,
        unit: this.unit,
        id: this.id,
        total: this.total);
  }

  Map toSubmitInfo(String officeId) {
    return {
      "materialId": this.id,
      "materialName": this.materialName,
      "materialType": this.materialType,
      "assetType": this.assetType,
      "assetTypeName": assetTypeName,
      "brand": brand,
      "model": model,
      "specification": specification,
      "attatchId": attatchId,
      "path": path,
      "unit": unit,
      "quantity": quantity,
      "officeId": officeId,
    };
  }
}
